<?

class generate_model_task extends system_task
{
	public function execute( array $params = array() )
	{
		if ( !$this->model_type = $params[0] ) return $this->error('Provide model type');
		if ( !$this->model_name = $params[1] ) return $this->error('Provide model name');

		$template_folder = realpath(dirname(__FILE__) . '/../../../assets/generate/lib/model') . '/' . $this->model_type;
		if ( !is_dir($template_folder) ) return $this->error('Invalid model type');

		$this->project = basename(getcwd());
		$this->path = getcwd();
		
		$this->out('Generating model ' . $this->model_name . ' for ' . $this->project);

		$model_dir = $this->path . '/lib/model';
		if ( !is_dir($model_dir) ) mkdir($model_dir, 0777, true);

		$model_base_dir = $this->path . '/lib/model/base';
		if ( !is_dir($model_base_dir) ) mkdir($model_base_dir, 0777, true);

		$base_file = $model_base_dir . '/' . $this->model_name . '.base.peer.php';
		$this->copy($template_folder . '/base.peer.php', $base_file);
		
		if ( !is_file($model_dir . '/' . $this->model_name . '.peer.php') )
			$this->copy($template_folder . '/peer.php', $model_dir . '/' . $this->model_name . '.peer.php');

		$this->out('Generated two files');
	}

	protected function copy( $src, $dst )
	{
		$content = file_get_contents($src);
		
		if ( is_file($dst) )
		{
			preg_match_all('/const (.+?) .+?;/', file_get_contents($dst), $m);
			
			foreach ( $m[1] as $i => $const )
				$content = preg_replace("/const {$const} .+?;/", $m[0][$i], $content);
		}
		
		$content = str_replace(
			array('{$name}', '{$path}', '{$project}'),
			array($this->model_name, $this->path, $this->project),
			$content
		);

		file_put_contents($dst, $content);
	}
}